package com.dimeng.adapter;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.dimeng.entity.MettlePhotoAlumb;
import com.dimeng.entity.MettleViewCache;
import com.dimeng.utils.AsyncImageLoader;
import com.dimeng.utils.AsyncImageLoader.ImageCallback;

/**
 * @author write by ccn<br>
 *         <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-7-02 下午7:11:00<br>
 *          descrition:美图视图的item视图缓存
 */
public class MettleAdapter extends ArrayAdapter<MettlePhotoAlumb> {
	private AbsListView absListView;
	private int resourceId;
	private AsyncImageLoader asyncImageLoader = AsyncImageLoader.getInstance();
	public MettleAdapter(Context c, List<MettlePhotoAlumb> list, AbsListView absListView,int resourceId) {
		super(c, 0, list);
		this.absListView = absListView;
		this.resourceId = resourceId;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Activity activity = (Activity) getContext();
		View view = convertView;
		MettlePhotoAlumb alum = getItem(position);
		MettleViewCache mettleViewCache;
		if (view == null) {
			LayoutInflater inflater = activity.getLayoutInflater();
			view = inflater.inflate(resourceId, null);
			mettleViewCache = new MettleViewCache(view);
			view.setTag(mettleViewCache);
		} else {
			mettleViewCache = (MettleViewCache) view.getTag();
		}
		ImageView imageView = mettleViewCache.getImageView();
		if (null != alum) {
			String imageUrl = alum.getImageUrl();
			imageView.setTag(imageUrl);
			Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl,
					new ImageCallback() {
						public void imageLoaded(Drawable imageDrawable,
								String imageUrl) {
							ImageView imageViewByTag = (ImageView) absListView.findViewWithTag(imageUrl);
							if (imageViewByTag != null) {
								imageViewByTag.setImageDrawable(imageDrawable);
							}
						}
					});
			imageView.setImageDrawable(cachedImage);
			TextView alumIdTextView = mettleViewCache.getAlumIdTextView();
			if(null != alumIdTextView){
				alumIdTextView.setText(alum.getAblumId()+"");
			}
			TextView albumNameTextView = mettleViewCache.getAlbumNameTextView();
			if(null != albumNameTextView){
				albumNameTextView.setText(alum.getAblumName());
			}
		}
		return view;
	}
}
